package com.ternnetwork.auth.server.service;

import com.ternnetwork.commons.utils.HttpClientUtils;
import com.ternnetwork.commons.utils.JsonUtils;
import com.ternnetwork.core.configuration.service.DataDictionaryService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;

@Service
@Slf4j
public class WeChatAuthServiceImpl implements WeChatAuthService{

    private final DataDictionaryService dataDictionaryService;

    public WeChatAuthServiceImpl(DataDictionaryService dataDictionaryService) {
        this.dataDictionaryService = dataDictionaryService;
    }


    public Map jsCodeToSession(String jsCode,String appId){

        String appSecret=dataDictionaryService.getValueByKey("app.wechatapp.".concat(appId));

        //得到微信返回code临时票据
        //拿着code + 小程序id + 小程序密钥 请求微信接口服务
        //请求微信接口服务，返回两个值session_key和openId
        StringBuffer url = new StringBuffer()
                .append("https://api.weixin.qq.com/sns/jscode2session")
                .append("?appid=%s")
                .append("&secret=%s")
                .append("&js_code=%s")
                .append("&grant_type=authorization_code");
        String tokenUrl = String.format(url.toString(), appId, appSecret, jsCode);
        String result;
        try {
            result = HttpClientUtils.get(tokenUrl);
        }catch (Exception e){
            throw new RuntimeException();
        }
        Map resultMap=JsonUtils.jsonToObject(result, HashMap.class);

        return resultMap;

    }
}
